package 构建模式;



import testJ.test1;
import java.util.ArrayList;
import java.util.List;

public class 观察者模式 {
    public static void main(test1[] args) {
        Supject supject = new Supject();
        Test1 test1 = new Test1();
        supject.addObserver(test1);
        Test2 test2 = new Test2();
        supject.addObserver(test2);
        //调用观察者
        supject.notifyObserver("数据变化了");
    }
}
//观察者容器
class Supject{
    //容器，是有实现Observer接口才是观察者
    private List<Obsever> container = new ArrayList<>();
    public void addObserver(Obsever obsever){
        container.add(obsever);
    }
    public void removeObserver(Obsever obsever){
        container.remove(obsever);
    }
    public void notifyObserver(Object object){
        container.forEach(e->{
            e.update(object);
        });
    }
}
interface Obsever{
    void update(Object object);
}
class Test1 implements Obsever{

    @Override
    public void update(Object object) {
        System.out.println("观察者1："+object);
    }
}
class Test2 implements Obsever{

    @Override
    public void update(Object object) {
        System.out.println("观察者2："+object);
    }
}